package com.sfx.messagequeue.mqServer.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

import static com.sfx.messagequeue.mqServer.core.ExchangeType.DIRECT;

/**
 * Created with IntelliJ IDEA.
 * Description: 交换机-->相当于前台接收生产者的消息
 * User: sfx
 * Date: 2023-07-30
 * Time: 18:03
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class Exchange {
    //交换机的唯一身份标识
    private String name;
    //交换机是否持久化,true表示支持持久化,false不支持持久化
    private boolean durable = false;
    //交换机是否自动删除(如果没有交换机没有使用是否自动删除) true:删除,false:不删除
    private boolean autoDelete = false;
    //交换机的类型->默认为直接交换机
    private ExchangeType type = DIRECT;
    //交换机的选项-->一些额外的功能
    //由于数据库没有Map类型,所以我们需要将Map转化为String类型
    private Map<String, Object> arguments = new HashMap<>();

    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String arguments = objectMapper.writeValueAsString(this.arguments);
            return arguments;
        } catch (JsonProcessingException e) {
            log.error("arguments转Map错误 {}", e);
            e.printStackTrace();
        }
        //抛出异常返回空的字符串
        return "{}";
    }

    public void setArguments(String arguments) {
        //转换成arguments-->Map类型
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            //将String类型转换成arguments
            Map<String, Object> readValue = objectMapper.readValue(arguments, new TypeReference<Map<String, Object>>() {
            });
            this.arguments = readValue;
        } catch (JsonProcessingException e) {
            log.error("arguments转Map错误 {}", e);
            e.printStackTrace();
        }
    }

    /**
     * 用于测试
     * @param key
     * @param val
     */
    public void setArguments(String key, String val) {
        arguments.put(key, val);
    }

    public Object getArguments(String key) {
        return arguments.get(key);
    }
}